package com.study.interceptor;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 登录拦截器
 *
 * @author huang
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 过滤器不能注释 bean
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 进入接口方法前触发
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Object key = stringRedisTemplate.opsForValue().get("key");

        // 请求头参数
        String token1 = request.getHeader("token");

        // 获取请求参数, 进行验证( filter 只能跳转页面, 拦截器可以返回类容 )
        String token = request.getParameter("token");

        // 放行
        if (StringUtils.isEmpty(token)) {
            response.getWriter().print("token err");
            return false;
        }
        // 拒绝请求
        return true;
    }

    /**
     * 接口调用之后, 试图渲染之前触发
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 试图渲染完成之后触发, 标志着接口调用流程结束, 通常用于资源清理
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
